package com.unistec.fileserver.server.biz;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hnit.common.biz.BaseBiz;
import com.unistec.fileserver.client.entity.Resource;
import com.unistec.fileserver.server.UploadFactory;
import com.unistec.fileserver.server.mapper.ResourceMapper;
import com.unistec.fileserver.server.provider.IStorageProvider;
import com.unistec.framework.utils.Objects;

/**
 * 文件服务器业务类
 * 
 * @description
 * @author 胡晓光
 * @date 2021-9-29
 * @time 13:57:07
 *
 */
@Service
public class FileServerService extends BaseBiz<ResourceMapper, Resource> {
	Logger logger = LoggerFactory.getLogger(FileServerService.class);

	@Autowired
	UploadFactory uploadFactory;

	/**
	 * 删除24小时以外的资源
	 * 
	 * @description
	 * @author 胡晓光
	 * @date 2021-9-29
	 * @time 13:58:32
	 *
	 */
	@Transactional
	public void deleteResourceOlderThan24Hours() {
		// 获取所有超过24小时的资源文件
		IStorageProvider storageProvider = uploadFactory.getStoragetProvider();
		List<Resource> resources = this.mapper.getResourceOlderThan24Hours();
		if (Objects.nonNull(resources)) {
			for (Resource r : resources) {
				try {
					storageProvider.deleteFile(null, r.getForeignIdentity());
				} catch (Exception e) {
					logger.error("[Storage] 清理临时文件，删除文件[id: " + r.getId() + ", name:" + r.getName() + ",url:" + r.getUrl() + "]时失败！", e);
				}
			}
		}
		this.mapper.deleteResourceOlderThan24Hours();
	}

	/**
	 * 根据唯一键来查找资源
	 * 
	 * @description
	 * @author 胡晓光
	 * @date 2021-9-30
	 * @time 10:48:42
	 * 
	 * @param foreignIds
	 */
	public List<Resource> getResourceInfoByUnique(List<String> foreignIds) {
		List<Resource> results = new ArrayList<>();
		if (Objects.nonNull(foreignIds)) {
			for (String id : foreignIds) {
				results.add(this.mapper.selectOneByUnique(id));
			}
		}
		return results;
	}

	/**
	 * 根据唯一键来查找资源
	 * 
	 * @description
	 * @author 胡晓光
	 * @date 2021-9-30
	 * @time 10:48:42
	 * 
	 * @param foreignIds
	 */
	public Resource getResourceInfoByUnique(String unique) {
		try {
			return this.mapper.selectOneByUnique(unique);
		} catch (Exception e) {
			return null;
		}
	}
}
